{{- $analytics := .Scratch.Get "analytics" | default dict -}}

{{- /* Google Analytics */ -}}
{{- $google := $analytics.google.id | default site.Config.Services.GoogleAnalytics.ID -}}
{{- with $google -}}
    {{- if strings.HasPrefix (lower .) "ua-" -}}
        {{- warnf "Google Analytics 4 (GA4) replaced Google Universal Analytics (UA) effective 1 July 2023. See https://support.google.com/analytics/answer/11583528. Create a GA4 property and data stream, then replace the Google Analytics ID in your site configuration with the new value." -}}
    {{- else -}}
        {{- $respectDoNotTrack := $analytics.google.respectDoNotTrack | default site.Config.Privacy.GoogleAnalytics.RespectDoNotTrack -}}
        <script>
            var doNotTrack = false;
            if ({{ $respectDoNotTrack }}) {
                var dnt = (navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack);
                var doNotTrack = (dnt == "1" || dnt == "yes");
            }
            if (!doNotTrack) {
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());
                gtag('config', '{{ . }}');
            }
        </script>
        {{- printf "https://www.googletagmanager.com/gtag/js?id=%v" . | dict "Async" true "Source" | partial "plugin/script.html" -}}
    {{- end -}}
{{- end -}}

{{- /* Fathom Analytics */ -}}
{{- with $analytics.fathom.id -}}
    <script>
        window.fathom=window.fathom||function(){(fathom.q=fathom.q||[]).push(arguments);};
        fathom('set', 'siteId', '{{ . }}');
        fathom('trackPageview');
    </script>
    {{- dict "Source" ($analytics.fathom.server | default "cdn.usefathom.com" | printf "https://%v/tracker.js") "Async" true "Attr" "id=fathom-script" | partial "plugin/script.html" -}}
{{- end -}}

{{- /* Plausible Analytics */ -}}
{{- with $analytics.plausible.dataDomain -}}
    {{- dict "Source" "https://plausible.io/js/plausible.js" "Async" true "Defer" true "Attr" ($analytics.plausible.dataDomain | printf `data-domain="%v"`) | partial "plugin/script.html" -}}
{{- end -}}

{{- /* Yandex Metrica */ -}}
{{- with $analytics.yandexMetrica.id -}}
    <script>
       (function(m,e,t,r,i,k,a){m[i]=m[i]||function(){(m[i].a=m[i].a||[]).push(arguments)};
       m[i].l=1*new Date();k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a)})
       (window, document, "script", "https://mc.yandex.ru/metrika/tag.js", "ym");

       ym({{ . }}, "init", {
            clickmap:true,
            trackLinks:true,
            accurateTrackBounce:true
       });
    </script>
    <noscript><div><img src="https://mc.yandex.ru/watch/{{ . }}" style="position:absolute; left:-9999px;" alt="" /></div></noscript>
{{- end -}}
